package com.qiye.pointsserver.controller;



import com.qiye.pointsserver.common.result.Result;
import com.qiye.pointsserver.service.EmailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/v1/email")
@Tag(name="06.邮件模块接口")
public class EmailController {

    @Resource
    private EmailService emailService;

    @Resource
    RedisTemplate<String, Object> redisTemplate;


    @PostMapping("/code")
    @Operation(summary = "发送验证码")
    public Result sendCode(@RequestParam(value = "toEmail") String toEmail){
        // 生成随机的六位验证码
        Random random = new Random();
        int code = random.nextInt(900000) + 100000;
        String email = toEmail;
        String subject = "注册验证码";
        String text = "验证码："+code+",3分钟内有效，请勿泄露给他人，如非本人操作，请忽略本邮件。";
        try {
            emailService.sendSimpleMessage(email, subject, text);
            // 将验证码存入Redis，设置过期时间为5分钟
            String key =  "验证码"+toEmail;
            redisTemplate.opsForValue().set(key, code, 3, TimeUnit.MINUTES);
            return  Result.success("验证码发送成功");

        } catch (Exception e){
            return Result.failed("邮件发送失败");
        }
    }

}
